//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.menggudf.http;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class HttpURLConnectionUtils {
    private static Log logger = LogFactory.getLog(HttpURLConnectionUtils.class);

    public HttpURLConnectionUtils() {
    }

    public static String connection(String strUrl, Map<String, String> parameters) throws Exception {
        return connection(strUrl, "POST", parameters, "UTF-8");
    }

    public static String connection(String strUrl, Map<String, String> parameters, int timeout) throws Exception {
        return connection(strUrl, "POST", parameters, "UTF-8", timeout);
    }

    public static String connection(String strUrl, String method, Map<String, String> parameters, String encode) throws Exception {
        return connection(strUrl, method, (Map)parameters, encode, 60);
    }

    public static String connection(String strUrl, String method, Map<String, String> parameters, String encode, int timeout) throws Exception {
        return connection(strUrl, method, 1, (Map)parameters, encode, timeout);
    }

    public static String connection(String strUrl, String method, int retryTimes, Map<String, String> parameters, String encode, int timeout) throws Exception {
        return connection(strUrl, method, retryTimes, parameters, encode, timeout, timeout);
    }

    public static String connection(String strUrl, String method, int retryTimes, Map<String, String> parameters, String encode, int connectTimeout, int readTimeout) throws Exception {
        return connection(strUrl, method, (Map)null, retryTimes, (Map)parameters, encode, connectTimeout, readTimeout);
    }

    public static String connection(String strUrl, String method, Map<String, Object> headers, int retryTimes, Map<String, String> parameters, String encode, int connectTimeout, int readTimeout) throws Exception {
        long start = System.currentTimeMillis();
        new String();
        URL url = null;
        HttpURLConnection httpurlconnection = null;
        if (parameters == null) {
            parameters = new HashMap();
        }

        String var17;
        try {
            if (strUrl.startsWith("https://")) {
                HttpsCertificates.trustAllHttpsCertificates();
            }

            url = new URL(strUrl);
            String header;
            if ("get".equalsIgnoreCase(method)) {
                header = strUrl + (strUrl.indexOf("?") == -1 ? "?1=1" : "");
                header = header + readParameter((Map)parameters, encode);
                url = new URL(header);
            }

            httpurlconnection = (HttpURLConnection)url.openConnection();
            if (httpurlconnection instanceof HttpsURLConnection) {
                ((HttpsURLConnection)httpurlconnection).setHostnameVerifier(new HostnameVerifier() {
                    public boolean verify(String s, SSLSession sslsession) {
                        return true;
                    }
                });
            }

            httpurlconnection.setConnectTimeout(1000 * connectTimeout);
            httpurlconnection.setReadTimeout(1000 * readTimeout);
            httpurlconnection.setDoOutput("post".equalsIgnoreCase(method));
            httpurlconnection.setDoInput(true);
            httpurlconnection.setUseCaches(false);
            if (headers != null) {
                Iterator var23 = headers.keySet().iterator();

                while(var23.hasNext()) {
                    header = (String)var23.next();
                    httpurlconnection.setRequestProperty(header, String.valueOf(headers.get(header)));
                }
            }

            httpurlconnection.setRequestMethod(method);
            if ("post".equalsIgnoreCase(method)) {
                writeParameter(httpurlconnection.getOutputStream(), (Map)parameters, encode);
                httpurlconnection.getOutputStream().flush();
                httpurlconnection.getOutputStream().close();
            }

            httpurlconnection.connect();
            long end = System.currentTimeMillis();
            int code = httpurlconnection.getResponseCode();
            logger.debug("请求【" + strUrl + "】【" + method + "】【" + encode + "】【" + (parameters.toString().length() < 1000 ? parameters.toString() : parameters.toString().substring(0, 1000) + "...") + "】返回状态【" + code + "】耗时【" + (end - start) + "】");
            if (code != 200) {
                throw new HttpException(code, "请求【" + strUrl + "】【" + method + "】【" + encode + "】【" + (parameters.toString().length() < 1000 ? parameters.toString() : parameters.toString().substring(0, 1000) + "...") + "】返回错误状态【" + code + "】耗时【" + (end - start) + "】，请与系统管理员联系！");
            }

            String result = getResult(httpurlconnection.getInputStream(), encode);
            return result;
        } catch (Exception var20) {
            long end = System.currentTimeMillis();
            if (retryTimes == 1) {
                if (var20 instanceof HttpException) {
                    throw var20;
                }

                throw new Exception("请求【" + strUrl + "】【" + method + "】【" + encode + "】【" + (parameters.toString().length() < 1000 ? parameters.toString() : parameters.toString().substring(0, 1000) + "...") + "】耗时【" + (end - start) + "】错误:" + var20.getMessage(), var20);
            }

            logger.error("第【" + retryTimes + "】次请求【" + strUrl + "】【" + method + "】【" + encode + "】【" + (parameters.toString().length() < 1000 ? parameters.toString() : parameters.toString().substring(0, 1000) + "...") + "】耗时【" + (end - start) + "】错误:" + var20.getMessage(), var20);
            --retryTimes;
            logger.debug("开始第【" + retryTimes + "】次请求【" + strUrl + "】【" + method + "】【" + encode + "】【" + (parameters.toString().length() < 1000 ? parameters.toString() : parameters.toString().substring(0, 1000) + "...") + "】...");
            var17 = connection(strUrl, method, retryTimes, (Map)parameters, encode, connectTimeout, readTimeout);
        } finally {
            if (httpurlconnection != null) {
                httpurlconnection.disconnect();
            }

        }

        return var17;
    }

    public static String connection(String strUrl, String method, String parameters, String encode) throws Exception {
        return connection(strUrl, method, (String)parameters, encode, 60);
    }

    public static String connection(String strUrl, String method, String parameters, String encode, int timeout) throws Exception {
        return connection(strUrl, method, 1, (String)parameters, encode, timeout);
    }

    public static String connection(String strUrl, String method, int retryTimes, String parameters, String encode, int timeout) throws Exception {
        return connection(strUrl, method, retryTimes, parameters, encode, timeout, timeout);
    }

    public static String connection(String strUrl, String method, int retryTimes, String parameters, String encode, int connectTimeout, int readTimeout) throws Exception {
        return connection(strUrl, method, (Map)null, retryTimes, (String)parameters, encode, connectTimeout, readTimeout);
    }

    public static String connection(String strUrl, String method, Map<String, Object> headers, int retryTimes, String parameters, String encode, int connectTimeout, int readTimeout) throws Exception {
        if ("get".equalsIgnoreCase(method)) {
            throw new Exception("传输数据流必须为GET请求方式，请与系统管理员联系！");
        } else {
            long start = System.currentTimeMillis();
            new String();
            URL url = null;
            HttpURLConnection httpurlconnection = null;
            if (StringUtils.isEmpty(parameters)) {
                parameters = "";
            }

            String var17;
            try {
                if (strUrl.startsWith("https://")) {
                    HttpsCertificates.trustAllHttpsCertificates();
                }

                url = new URL(strUrl);
                httpurlconnection = (HttpURLConnection)url.openConnection();
                if (httpurlconnection instanceof HttpsURLConnection) {
                    ((HttpsURLConnection)httpurlconnection).setHostnameVerifier(new HostnameVerifier() {
                        public boolean verify(String s, SSLSession sslsession) {
                            return true;
                        }
                    });
                }

                httpurlconnection.setConnectTimeout(1000 * connectTimeout);
                httpurlconnection.setReadTimeout(1000 * readTimeout);
                httpurlconnection.setDoOutput("POST".equalsIgnoreCase(method));
                httpurlconnection.setDoInput(true);
                httpurlconnection.setUseCaches(false);
                httpurlconnection.setRequestProperty("Content-Type", "text/html");
                httpurlconnection.setRequestProperty("Accept-Charset", encode);
                httpurlconnection.setRequestProperty("contentType", encode);
                if (headers != null) {
                    Iterator var23 = headers.keySet().iterator();

                    while(var23.hasNext()) {
                        String header = (String)var23.next();
                        httpurlconnection.setRequestProperty(header, String.valueOf(headers.get(header)));
                    }
                }

                httpurlconnection.setRequestMethod(method);
                if (!StringUtils.isEmpty(parameters)) {
                    httpurlconnection.getOutputStream().write(parameters.getBytes(encode));
                }

                httpurlconnection.getOutputStream().flush();
                httpurlconnection.getOutputStream().close();
                httpurlconnection.connect();
                long end = System.currentTimeMillis();
                int code = httpurlconnection.getResponseCode();
                logger.debug("请求【" + strUrl + "】【" + method + "】【" + encode + "】【" + (parameters.length() < 1000 ? parameters : parameters.substring(0, 1000) + "...") + "】返回状态【" + code + "】耗时【" + (end - start) + "】");
                if (code != 200) {
                    throw new HttpException(code, "请求【" + strUrl + "】【" + method + "】【" + encode + "】【" + (parameters.length() < 1000 ? parameters : parameters.substring(0, 1000) + "...") + "】返回错误状态【" + code + "】耗时【" + (end - start) + "】，请与系统管理员联系！");
                }

                String result = getResult(httpurlconnection.getInputStream(), encode);
                return result;
            } catch (Exception var20) {
                long end = System.currentTimeMillis();
                if (retryTimes == 1) {
                    if (var20 instanceof HttpException) {
                        throw var20;
                    }

                    throw new Exception("请求【" + strUrl + "】【" + method + "】【" + encode + "】【" + (parameters.length() < 1000 ? parameters : parameters.substring(0, 1000) + "...") + "】耗时【" + (end - start) + "】错误:" + var20.getMessage(), var20);
                }

                logger.error("第【" + retryTimes + "】次请求【" + strUrl + "】【" + method + "】【" + encode + "】【" + (parameters.length() < 1000 ? parameters : parameters.substring(0, 1000) + "...") + "】耗时【" + (end - start) + "】错误:" + var20.getMessage(), var20);
                --retryTimes;
                logger.debug("开始第【" + retryTimes + "】次请求【" + strUrl + "】【" + method + "】【" + encode + "】【" + (parameters.length() < 1000 ? parameters : parameters.substring(0, 1000) + "...") + "】...");
                var17 = connection(strUrl, method, retryTimes, parameters, encode, connectTimeout, readTimeout);
            } finally {
                if (httpurlconnection != null) {
                    httpurlconnection.disconnect();
                }

            }

            return var17;
        }
    }

    public static String getResult(InputStream inputStream, String encode) throws Exception {
        StringBuffer result = new StringBuffer();
        if(Objects.isNull(inputStream)){
            return null;
        }
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, encode));
        String lineSeparator = System.getProperty("line.separator");

        String inputLine;
        for(int lineNumber = 0; (inputLine = bufferedReader.readLine()) != null; result.append(inputLine)) {
            ++lineNumber;
            if (lineNumber != 1) {
                result.append(lineSeparator);
            }
        }

        return result.toString();
    }

    public static boolean isURLExist(String url) {
        try {
            if (url.startsWith("https://")) {
                HttpsCertificates.trustAllHttpsCertificates();
            }

            URL u = new URL(url);
            HttpURLConnection urlconn = (HttpURLConnection)u.openConnection();
            int state = urlconn.getResponseCode();
            return state == 200;
        } catch (Exception var4) {
            return false;
        }
    }

    public static String encodeURL(String url, String encode) {
        try {
            return URLEncoder.encode(url, encode);
        } catch (UnsupportedEncodingException var3) {
            logger.error("对url【" + url + "】进行【" + encode + "】编码错误：" + var3.getMessage(), var3);
            return null;
        }
    }

    public static String decodeURL(String url, String encode) {
        try {
            return URLDecoder.decode(url, encode);
        } catch (UnsupportedEncodingException var3) {
            logger.error("对url【" + url + "】进行【" + encode + "】解码错误：" + var3.getMessage(), var3);
            return null;
        }
    }

    public static String getParamString(Map<String, String[]> params, String encode) {
        StringBuffer queryString = new StringBuffer(256);
        Iterator<String> it = params.keySet().iterator();
        int count = 0;

        while(it.hasNext()) {
            String key = (String)it.next();
            String[] param = (String[])params.get(key);

            for(int i = 0; i < param.length; ++i) {
                if (count == 0) {
                    ++count;
                } else {
                    queryString.append("&");
                }

                queryString.append(key);
                queryString.append("=");

                try {
                    queryString.append(URLEncoder.encode(param[i], encode));
                } catch (UnsupportedEncodingException var9) {
                }
            }
        }

        return queryString.toString();
    }

    public static String getRequestURL(HttpServletRequest request, String encode) {
        StringBuffer originalURL = new StringBuffer(request.getServletPath());
        Map<String, String[]> parameters = request.getParameterMap();
        if (parameters != null && parameters.size() > 0) {
            originalURL.append("?");
            originalURL.append(getParamString(parameters, encode));
        }

        return originalURL.toString();
    }

    private static void writeParameter(OutputStream out, Map<String, String> parameterMap, String encode) throws Exception {
        if (parameterMap != null) {
            Iterator var6 = parameterMap.entrySet().iterator();

            while(var6.hasNext()) {
                Map.Entry<String, String> parameter = (Map.Entry)var6.next();
                String value = (String)parameter.getValue();
                if (StringUtils.isEmpty(value)) {
                    value = "";
                }

                String temp = "&" + (String)parameter.getKey() + "=" + URLEncoder.encode(value, encode);
                out.write(temp.getBytes());
            }
        }

    }

    private static String readParameter(Map<String, String> parameterMap, String encode) throws Exception {
        StringBuffer parameters = new StringBuffer();
        if (parameterMap != null) {
            Iterator var6 = parameterMap.entrySet().iterator();

            while(var6.hasNext()) {
                Map.Entry<String, String> parameter = (Map.Entry)var6.next();
                String value = (String)parameter.getValue();
                if (StringUtils.isEmpty(value)) {
                    value = "";
                }

                String temp = "&" + (String)parameter.getKey() + "=" + URLEncoder.encode(value, encode);
                parameters.append(temp);
            }
        }

        return parameters.toString();
    }

    public static void main(String[] args) throws Exception {
        String strUrl = "http://localhost:8080/cross/client/declare/declarePaymentOrder.action";
        String method = "POST";
        String postdata = null;
        Map<String, String> parameters = new HashMap();
        String encode = "UTF-8";
        parameters.put("payTransactionNo", "2016102721001003100200123591");
        parameters.put("payAmount", "10.00");
        parameters.put("payAmountCurr", "142");
        parameters.put("payTimeStr", "2016-10-27 14:01:52");
        parameters.put("notify_time", "2016-10-27 14:02:12");
        parameters.put("sign_type", "RSA");
        parameters.put("payMerchantCode", "2088101122136241");
        parameters.put("payAccount", "2088102000979107");
        parameters.put("eCommerceCode", "test20161027");
        parameters.put("payerCertType", "01");
        parameters.put("payEnterpriseCode", "guangzhoudz");
        parameters.put("notify_type", "forex_customs_info");
        parameters.put("sign", "GBw6ONKO+ptNqbGQgM35fi3ArDRxW6ZJkYiqkOD4qQnX9wBE3e6az3dBXHJSPqT3YdK6hgmNdMJNvNHZwPiuLpT/E7MdJiFWTM1nGV613Ht/Ts/r74tLcUq8yoJoIZmbtmoQu2GHVu2pjTRZSeRhWsR29UYjxw7cU4OcCQUg9vA=");
        parameters.put("payerCertNo", "220112198506020534");
        parameters.put("_input_charset", "utf-8");
        parameters.put("payGoodsAmount", "10.00");
        parameters.put("orderNo", "5653345150254550");
        parameters.put("freight", "0");
        parameters.put("payTaxAmount", "0");
        parameters.put("payEnterpriseName", "支付宝（中国）网络技术有限公司");
        parameters.put("notify_id", "27d5bcd7f4f587b480aabdf94dd12fel0m");
        parameters.put("payerName", "边琪");
        String result = connection(strUrl, method, (Map)parameters, encode);
        System.out.println(result);
    }
}
